<template>
  <div class="profile-container">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <el-button text @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回首页
          </el-button>
        </div>
        <div class="header-center">
          <h2>用户信息管理</h2>
        </div>
        <div class="header-right"></div>
      </el-header>

      <!-- 主内容区 -->
      <el-main class="main-content">
        <div class="profile-content">
          <el-card class="profile-card">
            <template #header>
              <div class="card-header">
                <span>个人信息</span>
              </div>
            </template>

            <div class="profile-info">
              <div class="avatar-section">
                <el-avatar :size="120" :src="userInfo.avatar">
                  <el-icon><UserFilled /></el-icon>
                </el-avatar>
                <el-button type="primary" size="small" class="change-avatar-btn" @click="showAvatarUpload = true">
                  更换头像
                </el-button>
              </div>

              <el-descriptions :column="1" border class="info-descriptions">
                <el-descriptions-item label="用户名">
                  {{ userInfo.username }}
                </el-descriptions-item>
                <el-descriptions-item label="真实姓名">
                  {{ userInfo.name }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号">
                  {{ userInfo.phone }}
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">
                  {{ userInfo.email }}
                </el-descriptions-item>
                <el-descriptions-item label="注册时间">
                  {{ formatTime(userInfo.createTime) }}
                </el-descriptions-item>
              </el-descriptions>

              <div class="action-buttons">
                <el-button type="primary" @click="showEditDialog = true">
                  <el-icon><Edit /></el-icon>
                  编辑信息
                </el-button>
                <el-button type="warning" @click="showPasswordDialog = true">
                  <el-icon><Lock /></el-icon>
                  修改密码
                </el-button>
                <el-button type="danger" @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>

    <!-- 编辑信息对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑个人信息" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="90px">
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateInfo" :loading="updateLoading">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="500px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="90px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 更换头像对话框 -->
    <el-dialog v-model="showAvatarUpload" title="更换头像" width="400px">
      <el-upload
        class="avatar-uploader-dialog"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="newAvatar" :src="newAvatar" class="avatar-preview" />
        <img v-else-if="userInfo.avatar" :src="userInfo.avatar" class="avatar-preview" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <template #footer>
        <el-button @click="showAvatarUpload = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateAvatar" :loading="avatarLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  UserFilled,
  Edit,
  Lock,
  SwitchButton,
  Plus
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { logout } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()

const showEditDialog = ref(false)
const showPasswordDialog = ref(false)
const showAvatarUpload = ref(false)
const updateLoading = ref(false)
const passwordLoading = ref(false)
const avatarLoading = ref(false)
const newAvatar = ref('')
const editFormRef = ref(null)
const passwordFormRef = ref(null)

const userInfo = ref({
  username: '',
  name: '',
  phone: '',
  email: '',
  avatar: '',
  createTime: ''
})

const editForm = reactive({
  name: '',
  phone: '',
  email: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const uploadUrl = computed(() => {
  return '/api/file/upload'
})

const uploadHeaders = computed(() => {
  return {
    'Authorization': `Bearer ${userStore.token}`
  }
})

const validatePhone = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const validateEmail = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入邮箱'))
  } else if (!/^[\w.-]+@[\w.-]+\.\w+$/.test(value)) {
    callback(new Error('请输入正确的邮箱'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const editRules = {
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { required: true, validator: validateEmail, trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const goBack = () => {
  router.push('/home')
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await logout()
    userStore.clearAuth()
    ElMessage.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error)
    }
  }
}

const handleUpdateInfo = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      updateLoading.value = true
      try {
        // 这里调用更新接口
        ElMessage.success('信息更新成功')
        userInfo.value = { ...userInfo.value, ...editForm }
        userStore.setUserInfo(userInfo.value)
        showEditDialog.value = false
      } catch (error) {
        console.error('更新失败:', error)
      } finally {
        updateLoading.value = false
      }
    }
  })
}

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        // 这里调用修改密码接口
        ElMessage.success('密码修改成功，请重新登录')
        showPasswordDialog.value = false
        
        // 清除登录状态
        setTimeout(() => {
          userStore.clearAuth()
          router.push('/login')
        }, 1500)
      } catch (error) {
        console.error('修改密码失败:', error)
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    newAvatar.value = response.data.fileUrl
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.msg || '头像上传失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

const handleUpdateAvatar = async () => {
  if (!newAvatar.value) {
    ElMessage.warning('请先上传新头像')
    return
  }
  
  avatarLoading.value = true
  try {
    // 这里调用更新头像接口
    userInfo.value.avatar = newAvatar.value
    userStore.setUserInfo(userInfo.value)
    ElMessage.success('头像更新成功')
    showAvatarUpload.value = false
    newAvatar.value = ''
  } catch (error) {
    console.error('更新头像失败:', error)
  } finally {
    avatarLoading.value = false
  }
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

const loadUserInfo = () => {
  // 从 store 加载用户信息
  const storeUserInfo = userStore.userInfo
  userInfo.value = { ...storeUserInfo }
  
  // 填充编辑表单
  editForm.name = storeUserInfo.name || ''
  editForm.phone = storeUserInfo.phone || ''
  editForm.email = storeUserInfo.email || ''
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-container {
  width: 100%;
  height: 100vh;
  background: #f0f2f5;
}

.header {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  align-items: center;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  padding: 0 30px;
}

.header-center {
  text-align: center;
}

.header-center h2 {
  margin: 0;
  color: #333;
}

.main-content {
  padding: 30px;
  display: flex;
  justify-content: center;
}

.profile-content {
  width: 100%;
  max-width: 800px;
}

.profile-card {
  min-height: 600px;
}

.profile-info {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  padding: 20px 0;
}

.change-avatar-btn {
  margin-top: 10px;
}

.info-descriptions {
  margin: 20px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

.avatar-uploader-dialog {
  display: flex;
  justify-content: center;
}

.avatar-uploader-dialog :deep(.el-upload) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader-dialog :deep(.el-upload:hover) {
  border-color: #409eff;
}

.avatar-preview {
  width: 200px;
  height: 200px;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
</style>





